<template>
  <div class="left-wrap">
    <div class="device-info">
      <el-descriptions
        title=""
        :column="1"
        border
        size="medium"
        :labelStyle="{
          whiteSpace: 'nowrap',
          width: '120px'
        }"
      >
        <el-descriptions-item label="设备ID">{{ source.deviceId }}</el-descriptions-item>
        <el-descriptions-item label="设备部署名称">{{ source.deploymentName }}</el-descriptions-item>
        <el-descriptions-item label="设备地址">{{ source.deploymentAddress }}</el-descriptions-item>
        <el-descriptions-item label="设备型号">{{ source.deviceName }}</el-descriptions-item>
        <el-descriptions-item label="设备状态">
          <dict-tag
            :options="dict.type.device_status"
            :value="source.deviceStatus"
          />
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <div class="block" v-for="item in screenshotData" :key="item.flag">
      <div class="screenshot" v-loading="item.loading">
        <el-image
          v-if="item.imgUrl"
          :src="item.imgUrl"
          fit="contain"
          class="screenshot-img"
          :preview-src-list="[item.imgUrl]"
        />
        <img v-else src="@/assets/images/screenshot.png" class="default-img">
        <div class="icon" @click="handleRefreshCurrentScreenshot(item.flag)">
          <img src="@/assets/images/refresh.png" class="refresh-icon"/>
        </div>
      </div>
      <div class="name">{{ item.title }}</div>
    </div>
  </div>
</template>

<script>
import {
  reqGetScreenshot,
  reqGetScreenshotLastTime,
  reqGetNewScreenshot,
  reqGetPublishScreenshot
} from "@/api/operationAndMonitoring/deviceMonitoring";

// 对应屏幕数据在screenshotData的下标映射
const screenFlagDataIndexMap = {1: 0, 2: 1}
const durationConfig = 30
export default {
  name: "LeftDeviceInfo",
  dicts: ['device_status'],
  props: {
    source: {
      type: Object,
      default() {
        return {}
      }
    },
    deviceId: {
      type: String
    },
    ipAddress: {
      type: String
    }
  },

  data() {
    return {
      screenshotData: [
        {title: '主屏快照', flag: 1, loading: false, imgUrl: '', timer: null, duration: durationConfig},
        {title: '辅屏快照', flag: 2, loading: false, imgUrl: '', timer: null, duration: durationConfig},
      ]
    }
  },

  methods: {
    // @descriptions 获取截图流水号
    // @param {string} screenFlag 屏幕名称 1=主屏 2=副屏
    // @param {string} messageCode	消息编码，后台生成的一个流水号  mqtt
    async getPublishScreenshot(ScreenFlag) {
      return new Promise(async (resolve, reject) => {
        try {
          const index = screenFlagDataIndexMap[ScreenFlag]
          this.screenshotData[index].loading = true;
          const res = await reqGetPublishScreenshot({
            deviceId: this.deviceId,
            screenFlag: ScreenFlag,
            ipAddress: this.ipAddress
          })
          if (res.data) {
            resolve(res.data)
          } else {
            this.$modal.msgWarning("获取截图流水号messageCode失败！")
            reject()
          }
        } catch (err) {
          reject()
          console.log("reqGetScreenshot 接口数据异常", err)
        }
      })
    },

    // @descriptions 获取数据库设备最后一次截图
    // @param {number} ScreenFlag 屏幕名称 1=主屏 2=副屏
    async getScreenshotLastTime(ScreenFlag) {
      const index = screenFlagDataIndexMap[ScreenFlag]
      try {
        this.screenshotData[index].loading = true;
        const res = await reqGetScreenshotLastTime({
          deviceId: this.deviceId,
          ScreenFlag
        })
        if (res.data) this.screenshotData[index].imgUrl = res.data;
      } catch (err) {
        console.log("reqGetScreenshotLastTime 接口数据异常", err)
      } finally {
        this.screenshotData[index].loading = false;
      }
    },

    // 处理刷新截图
    async handleRefreshCurrentScreenshot(ScreenFlag) {
      const index = screenFlagDataIndexMap[ScreenFlag]
      try {
        this.screenshotData[index].loading = true;
        const messageCode = await this.getPublishScreenshot(ScreenFlag)
        // 30秒轮询获取截图
        if (this.screenshotData[index].timer) return
        // 设置倒计时30秒
        this.screenshotData[index].duration = durationConfig
        this.screenshotData[index].timer = setInterval(() => {
          // 倒计时30秒轮询结束
          if (this.screenshotData[index].duration <= 0) return this.clearGetScreenshotInterval(index)
          this.screenshotData[index].duration -= 3
          console.log('轮询获取截图 倒计时', this.screenshotData[index].duration)
          reqGetScreenshotLastTime({
            ScreenFlag: ScreenFlag,
            messageCode
          }).then(result => {
            if (result.data) { //已获取到最新截图
              this.screenshotData[index].imgUrl = result.data;
              this.clearGetScreenshotInterval(index)
              this.$modal.msgSuccess("截图刷新成功！")
            }
          })
        }, 3000)

      } catch (err) {
        this.screenshotData[index].loading = false;
        console.log("reqGetScreenshot 接口数据异常", err)
      }
    },

    // 清除获取截图轮询定时器
    clearGetScreenshotInterval(index) {
      clearInterval(this.screenshotData[index].timer)
      this.screenshotData[index].timer = null
      this.screenshotData[index].loading = false;
    }
  },
  created() {
    // 获取主屏副屏在数据库的最后一次截图
    this.getScreenshotLastTime(1)
    this.getScreenshotLastTime(2)
  }
}
</script>

<style lang="scss" scoped>
.left-wrap {
  width: 350px;
  margin-right: 20px;

  .device-info {
    margin-bottom: 30px;
    background: red;

    .el-descriptions {
      font-size: 15px;

      ::v-deep .el-descriptions-item__content {
        word-break: break-all;
      }
    }

  }

  .block {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }

    .screenshot {
      position: relative;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 198px;
      background: #fff;
      border: 1px solid #DCDFE6;

      .refresh-icon {
        position: absolute;
        bottom: 10px;
        right: 10px;
        width: 26px;
        height: 26px;
        filter: drop-shadow(0px 0px 1px #666);
        cursor: pointer;
      }

      .default-img {
        display: block;
        width: 50px;
        height: 50px;
      }

      .screenshot-img {
        display: block;
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }

    .name {
      margin-top: 10px;
      font-size: 16px;
      text-align: center;
    }
  }
}

</style>
